import { Model, AppEvent } from "../../framework/framework";
import { FormatDateTime } from "../../framework/common";
import { CartonLogic, ClientStore } from "../logics/logic";

class CartonModel extends Model implements IModel {

    constructor(metiator: IMediator) {
        super(metiator);
    }

    public initialize() {
        this.subscribeToEvents([
            new AppEvent("app.model.carton.news_list", null, (e, args) => { this.news_list(args); }),
            new AppEvent("app.model.carton.news_add", null, (e, args) => { this.news_add(args); }),
            new AppEvent("app.model.carton.news_has", null, (e, args) => { this.news_has(args); }),
            new AppEvent("app.model.carton.user_login", null, (e, args) => { this.user_login(args); })
        ]);
    }

    public dispose() {
        this.unsubscribeToEvents();
    }

    private news_list(args: number[]): void {
        let lgc = new CartonLogic();

        lgc.getNewsList({ pageIndex: args[0], pageSize: args[1] }, (list) => {
            this.triggerEvent(new AppEvent("app.view.carton.news_article", list, null));
        });

    }
    private news_add(args: string[]): void {
        let lgc = new CartonLogic();

        lgc.addNewsData(<any>args, (list) => {
            this.triggerEvent(new AppEvent("app.view.carton.news_article", list, null));
        });
    }
    private news_has(args: string[]): void {
        let lgc = new CartonLogic();

        lgc.hasNewsData(<any>args[0], (list) => {
            this.triggerEvent(new AppEvent("app.view.carton.news_article", list, null));
        });
    }
    private user_login(args: string[]): void {
        let lgc = new CartonLogic();

        lgc.getLoginData(<any>args, (res) => {

            if (res && res.success && 200 === res.status) {
                // 保存登陆信息
                let lgcStore = new ClientStore("../../../clientSotre.json");
                let token = `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g, function (c) {
                    let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                }).toUpperCase();
                let time = new Date().getTime() + (1000 * 60 * 30); // 过期时间半个小时

                lgcStore.add(token, time, null);
            }

            this.triggerEvent(new AppEvent("app.view.carton.user_info", res, null));
        });
    }
}

export { CartonModel };
